<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessage } from 'element-plus'
// import { ElTag } from 'element-plus'
import { Icon } from '@/components/Icon'
import { Table } from '@/components/Table'
import { getTableListApi, saveTableApi,refreshUserBalanceApi,operatorNameApi,allrefreshUserBalanceApi } from '@/api/account'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/account/types'
import { ref, unref, reactive, computed, onMounted, onUnmounted, nextTick, watch, type Ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import Iohistory from './components/Iohistory.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { getGroupListApi } from '@/api/group'
import { isObject, isEmptyVal } from '@/utils/is'
import exp from 'constants'
// import { size } from 'lodash-es'

const ids = ref<number[]>([])
const refreshLoading = ref<Record<string, boolean>>({})
const route = useRoute()
const router = useRouter()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    
    // 手机端上拉加载时，如果正在加载更多数据，直接返回已有数据，避免重复请求
    if (isMobile.value && isLoadingMore.value) {
      return {
        list: unref(allDataList),
        total: total.value
      }
    }
    
    // 构建请求参数
    const requestParams: any = {
      page: unref(currentPage),
      pagesize: unref(pageSize),
      ...unref(searchParams)
    }
    
    // 添加排序参数（优先级：days > income > deposit > expenditure > lastexp > avgexp > balance > withdraw）
    if (daysOrderType.value !== null) {
      requestParams.orderWord = 'days'
      requestParams.orderType = daysOrderType.value
    } else if (incomeOrderType.value !== null) {
      requestParams.orderWord = 'income'
      requestParams.orderType = incomeOrderType.value
    } else if (depositOrderType.value !== null) {
      requestParams.orderWord = 'deposit'
      requestParams.orderType = depositOrderType.value
    } else if (expenditureOrderType.value !== null) {
      requestParams.orderWord = 'expenditure'
      requestParams.orderType = expenditureOrderType.value
    } else if (lastexpOrderType.value !== null) {
      requestParams.orderWord = 'lastexp'
      requestParams.orderType = lastexpOrderType.value
    } else if (avgexpOrderType.value !== null) {
      requestParams.orderWord = 'avgexp'
      requestParams.orderType = avgexpOrderType.value
    } else if (balanceOrderType.value !== null) {
      requestParams.orderWord = 'balance'
      requestParams.orderType = balanceOrderType.value
    } else if (withdrawOrderType.value !== null) {
      requestParams.orderWord = 'withdraw'
      requestParams.orderType = withdrawOrderType.value
    }
    
    const res = await getTableListApi(requestParams)
    
    // 获取接口返回的账户总余额 balSum
    if (res && res.data && res.data.balSum !== undefined) {
      const sum = typeof res.data.balSum === 'string' ? parseFloat(res.data.balSum) : (res.data.balSum || 0)
      balSum.value = isNaN(sum) ? 0 : sum
    }
    
    // 获取接口返回的账户总耗损 expSum
    if (res && res.data && res.data.expSum !== undefined) {
      const sum = typeof res.data.expSum === 'string' ? parseFloat(res.data.expSum) : (res.data.expSum || 0)
      expSum.value = isNaN(sum) ? 0 : sum
    }
    
    // 获取接口返回的账户总收益 incSum
    if (res && res.data && res.data.incSum !== undefined) {
      const sum = typeof res.data.incSum === 'string' ? parseFloat(res.data.incSum) : (res.data.incSum || 0)
      incSum.value = isNaN(sum) ? 0 : sum
    }
    
    // 获取接口返回的充值 deposit
    if (res && res.data && res.data.deposit !== undefined) {
      const sum = typeof res.data.deposit === 'string' ? parseFloat(res.data.deposit) : (res.data.deposit || 0)
      deposit.value = isNaN(sum) ? 0 : sum
    }
    
    // 获取接口返回的提现 withdraw
    if (res && res.data && res.data.withdraw !== undefined) {
      const sum = typeof res.data.withdraw === 'string' ? parseFloat(res.data.withdraw) : (res.data.withdraw || 0)
      withdraw.value = isNaN(sum) ? 0 : sum
    }
    
    // 获取接口返回的亏损账号数量 lossNum
    if (res && res.data && res.data.lossNum !== undefined) {
      const num = typeof res.data.lossNum === 'string' ? parseInt(res.data.lossNum) : (res.data.lossNum || 0)
      lossNum.value = isNaN(num) ? 0 : num
    }
    
    // 手机端使用累积数据，PC端使用分页数据
    if (isMobile.value) {
      if (unref(currentPage) === 1) {
        allDataList.value = res.data.items || []
        mobileCurrentPage.value = 1
      }
      const totalPages = Math.ceil(res.data.total / unref(pageSize))
      hasMoreData.value = unref(currentPage) < totalPages
      
      return {
        list: unref(allDataList),
        total: res.data.total
      }
    } else {
      return {
        list: res.data.items,
        total: res.data.total
      }
    }
  },
  fetchDelApi: async () => {
    const res = await delTableListApi(unref(ids))
    setTimeout(() => {
      saveLoading.value = false
      dialogVisible.value = false
    }, 1000)
    getList()
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

// 存储接口返回的账户总余额
const balSum = ref<number>(0)
// 存储接口返回的账户总耗损
const expSum = ref<number>(0)
// 存储接口返回的账户总收益
const incSum = ref<number>(0)
// 存储接口返回的充值
const deposit = ref<number>(0)
// 存储接口返回的提现
const withdraw = ref<number>(0)
// 存储接口返回的亏损账号数量
const lossNum = ref<number>(0)

const searchParams = ref({})
// days 字段排序状态：0降序，1升序，null无排序（默认0降序）
const daysOrderType = ref<0 | 1 | null>(0)
// income 字段排序状态
const incomeOrderType = ref<0 | 1 | null>(null)
// deposit 字段排序状态
const depositOrderType = ref<0 | 1 | null>(null)
// expenditure 字段排序状态
const expenditureOrderType = ref<0 | 1 | null>(null)
// lastexp 字段排序状态
const lastexpOrderType = ref<0 | 1 | null>(null)
// avgexp 字段排序状态
const avgexpOrderType = ref<0 | 1 | null>(null)
// balance 字段排序状态
const balanceOrderType = ref<0 | 1 | null>(null)
// withdraw 字段排序状态
const withdrawOrderType = ref<0 | 1 | null>(null)

const setSearchParams = (params: any) => {
  // 处理 grpids：如果包含 'all'，则设置为空数组
  if (params.grpids && Array.isArray(params.grpids)) {
    if (params.grpids.includes('all')) {
      params.grpids = []
    }
  }
  searchParams.value = params
  // 重置数据状态
  allDataList.value = []
  hasMoreData.value = true
  currentPage.value = 1
  mobileCurrentPage.value = 1
  // 重置排序状态为默认值（days字段0降序）
  daysOrderType.value = 0
  incomeOrderType.value = null
  depositOrderType.value = null
  expenditureOrderType.value = null
  lastexpOrderType.value = null
  avgexpOrderType.value = null
  balanceOrderType.value = null
  withdrawOrderType.value = null
  getList()
}

// 切换字段排序的通用函数
const toggleFieldSort = (field: string, orderTypeRef: Ref<0 | 1 | null>) => {
  // 只在PC端生效
  if (isMobile.value) return
  
  // 清除其他字段的排序状态
  if (field !== 'days') daysOrderType.value = null
  if (field !== 'income') incomeOrderType.value = null
  if (field !== 'deposit') depositOrderType.value = null
  if (field !== 'expenditure') expenditureOrderType.value = null
  if (field !== 'lastexp') lastexpOrderType.value = null
  if (field !== 'avgexp') avgexpOrderType.value = null
  if (field !== 'balance') balanceOrderType.value = null
  if (field !== 'withdraw') withdrawOrderType.value = null
  
  // 切换当前字段排序：0(降序) -> 1(升序) -> 0(降序)
  if (orderTypeRef.value === 0) {
    orderTypeRef.value = 1
  } else {
    orderTypeRef.value = 0
  }
  
  // 重置页码并重新获取数据
  currentPage.value = 1
  getList()
}

// 切换 days 排序
const toggleDaysSort = () => {
  toggleFieldSort('days', daysOrderType)
}

// 切换 income 排序
const toggleIncomeSort = () => {
  toggleFieldSort('income', incomeOrderType)
}

// 切换 deposit 排序
const toggleDepositSort = () => {
  toggleFieldSort('deposit', depositOrderType)
}

// 切换 expenditure 排序
const toggleExpenditureSort = () => {
  toggleFieldSort('expenditure', expenditureOrderType)
}

// 切换 lastexp 排序
const toggleLastexpSort = () => {
  toggleFieldSort('lastexp', lastexpOrderType)
}

// 切换 avgexp 排序
const toggleAvgexpSort = () => {
  toggleFieldSort('avgexp', avgexpOrderType)
}

// 切换 balance 排序
const toggleBalanceSort = () => {
  toggleFieldSort('balance', balanceOrderType)
}

// 切换 withdraw 排序
const toggleWithdrawSort = () => {
  toggleFieldSort('withdraw', withdrawOrderType)
}

// 手机端自动触发查询的防抖定时器
let mobileSearchTimer: NodeJS.Timeout | null = null

// 手机端自动触发查询的函数
const handleMobileAutoSearch = async () => {
  // 只在手机端触发
  if (!isMobile.value || !searchRef.value) return
  
  // 清除之前的定时器
  if (mobileSearchTimer) {
    clearTimeout(mobileSearchTimer)
  }
  
  // 防抖处理，300ms后执行查询，避免快速操作时频繁请求
  mobileSearchTimer = setTimeout(async () => {
    try {
      // 获取表单数据
      const formData = await searchRef.value.getFormData()
      
      // 过滤空值，与PC端Search组件的filterModel逻辑完全一致
      const filteredParams = Object.keys(formData).reduce((prev: any, next: string) => {
        const value = formData[next]
        if (!isEmptyVal(value)) {
          if (isObject(value)) {
            if (Object.keys(value).length > 0) {
              prev[next] = value
            }
          } else {
            prev[next] = value
          }
        }
        return prev
      }, {})
      
      // 处理 grpids：如果包含 'all'，则设置为空数组
      if (filteredParams.grpids && Array.isArray(filteredParams.grpids)) {
        if (filteredParams.grpids.includes('all')) {
          filteredParams.grpids = []
        }
      }
      
      // 触发查询，与PC端使用相同的参数处理逻辑
      setSearchParams(filteredParams)
    } catch (error) {
      console.error('手机端自动查询失败:', error)
    } finally {
      mobileSearchTimer = null
    }
  }, 300)
}

const { t } = useI18n()

// 响应式检测设备类型
const isMobile = ref(false)
const tableKey = ref(0) // 用于强制重新渲染表格

const checkIsMobile = () => {
  const wasMobile = isMobile.value
  isMobile.value = window.innerWidth <= 768
  
  // 如果设备类型发生变化，强制重新渲染表格
  if (wasMobile !== isMobile.value) {
    tableKey.value++
  }
}

// 立即检测一次设备类型
checkIsMobile()

// 上拉加载相关状态
const isLoadingMore = ref(false)
const hasMoreData = ref(true)
const allDataList = ref<any[]>([])
// 手机端当前页码（独立于 currentPage，避免触发 useTable 的 watch）
const mobileCurrentPage = ref(1)
// 分组选项
const groupOptions = ref<Array<{ label: string; value: string | number }>>([])
// 获取分组列表
const getGroupList = async () => {
  try {
    const res = await getGroupListApi()
    if (res && res.data) {
      // 添加"全部"选项
      const options = [
        { label: '全部', value: 'all' },
        ...res.data.items.map((item: any) => ({
          label: item.name,
          value: item.id
        }))
      ]
      groupOptions.value = options
    }
  } catch (error) {
    console.error('获取分组列表失败:', error)
  }
}

// 上拉加载更多数据
const loadMoreData = async () => {
  // 多重检查确保只在手机端执行
  if (!isMobile.value || isLoadingMore.value || !hasMoreData.value) {
    return
  }
  
  isLoadingMore.value = true
  
  
  try {
    // 计算下一页页码（使用手机端独立的页码变量）
    const nextPage = unref(mobileCurrentPage) + 1
    
    // 调用列表接口获取下一页数据
    const res = await getTableListApi({
      page: nextPage,
      pagesize: unref(pageSize),
      ...unref(searchParams)
    })
    
    if (res && res.data && res.data.items && res.data.items.length > 0) {
      // 先更新总数和状态，确保在触发 watch 前数据已更新
      total.value = res.data.total || 0
      
      // 将新数据追加到累积列表
      allDataList.value = [...unref(allDataList), ...res.data.items]
      
      // 手动更新表格显示的数据列表
      dataList.value = [...unref(allDataList)]
      
      // 更新手机端当前页码（分页+1）
      mobileCurrentPage.value = nextPage
      
      // 同步更新 currentPage 以便其他逻辑使用
      // 注意：这会触发 useTable 的 watch，但由于 fetchDataApi 中检查了 isLoadingMore，
      // 所以不会重复请求接口，而是直接返回已有数据
      currentPage.value = nextPage
      
      // 检查是否还有更多数据
      const totalPages = Math.ceil((res.data.total || 0) / unref(pageSize))
      hasMoreData.value = nextPage < totalPages
      
      // 调试信息
      if (import.meta.env.DEV) {
        console.log('加载更多数据成功:', {
          nextPage,
          totalPages,
          newItemsCount: res.data.items.length,
          totalItems: allDataList.value.length,
          hasMoreData: hasMoreData.value
        })
      }
    } else {
      hasMoreData.value = false
    }
  } catch (error) {
    console.error('加载更多数据失败:', error)
    hasMoreData.value = false
  } finally {
    isLoadingMore.value = false
  }
}

// 获取实际滚动容器
const getScrollContainer = (): HTMLElement | null => {
  // 尝试多种方式找到滚动容器
  // 1. ElScrollbar 的滚动容器
  const elScrollbar = document.querySelector('.layout-content-scrollbar .el-scrollbar__wrap') as HTMLElement
  if (elScrollbar) {
    return elScrollbar
  }
  
  // 2. 通用的 ElScrollbar 容器
  const scrollbar = document.querySelector('.el-scrollbar__wrap') as HTMLElement
  if (scrollbar) {
    return scrollbar
  }
  
  // 3. 返回 null，表示使用 window
  return null
}

// 获取滚动信息（从指定的容器或自动查找）
const getScrollInfo = (container?: HTMLElement | Window) => {
  let scrollTop = 0
  let scrollHeight = 0
  let clientHeight = 0
  
  if (container) {
    if (container === window) {
      // 使用 window 滚动信息
      scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
      scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight || 0
      clientHeight = document.documentElement.clientHeight || window.innerHeight || 0
    } else {
      // 使用容器滚动信息
      const el = container as HTMLElement
      scrollTop = el.scrollTop || 0
      scrollHeight = el.scrollHeight || 0
      clientHeight = el.clientHeight || 0
    }
  } else {
    // 自动查找容器
    const foundContainer = getScrollContainer()
    if (foundContainer) {
      scrollTop = foundContainer.scrollTop || 0
      scrollHeight = foundContainer.scrollHeight || 0
      clientHeight = foundContainer.clientHeight || 0
    } else {
      // 使用 window 滚动信息
      scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
      scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight || 0
      clientHeight = document.documentElement.clientHeight || window.innerHeight || 0
    }
  }
  
  return { scrollTop, scrollHeight, clientHeight }
}

// 滚动事件处理（仅手机端生效）
let scrollTimer: NodeJS.Timeout | null = null
const handleScroll = (event?: Event) => {
  // PC端直接返回，不处理滚动
  if (!isMobile.value) return
  
  // 获取触发事件的容器
  let scrollContainer: HTMLElement | Window | null = null
  if (event && event.target) {
    const target = event.target as HTMLElement
    // 检查是否是滚动容器本身
    if (target.classList.contains('el-scrollbar__wrap')) {
      scrollContainer = target
    } else {
      // 尝试查找父级滚动容器
      const parent = target.closest('.el-scrollbar__wrap') as HTMLElement
      if (parent) {
        scrollContainer = parent
      }
    }
  }
  
  // 如果没有找到容器，尝试使用 window
  if (!scrollContainer) {
    scrollContainer = window
  }
  
  // 防抖处理，避免频繁触发
  if (scrollTimer) {
    clearTimeout(scrollTimer)
  }
  
  scrollTimer = setTimeout(() => {
    // 检查是否正在加载或没有更多数据
    if (isLoadingMore.value || !hasMoreData.value) {
      if (import.meta.env.DEV) {
        console.log('跳过加载:', { isLoadingMore: isLoadingMore.value, hasMoreData: hasMoreData.value })
      }
      return
    }
    
    // 获取滚动信息（使用触发事件的容器）
    const { scrollTop, scrollHeight, clientHeight } = getScrollInfo(scrollContainer || undefined)
    
    // 距离底部100px时触发加载（增加触发距离）
    const threshold = 100
    const distanceToBottom = scrollHeight - scrollTop - clientHeight
    

    
    // 接近底部时触发加载
    if (distanceToBottom <= threshold && scrollHeight > clientHeight) {
      if (import.meta.env.DEV) {
      }
      loadMoreData()
    }
  }, 100) // 减少防抖时间到100ms
}

// 滚动监听器存储
const scrollListeners: Array<{ element: HTMLElement | Window; handler: (e?: Event) => void }> = []

// 添加滚动监听
const addScrollListener = () => {
  if (!isMobile.value) return
  
  // 清除旧监听器
  removeScrollListener()
  
  // 添加 window 滚动监听
  const windowHandler = (e: Event) => {
    // 传递事件对象
    handleScroll(e)
  }
  window.addEventListener('scroll', windowHandler, { passive: true })
  scrollListeners.push({ element: window, handler: windowHandler })
  
  // 尝试找到滚动容器并添加监听
  // 使用 setTimeout 确保 DOM 完全渲染
  setTimeout(() => {
    // 尝试多种选择器查找滚动容器
    let container: HTMLElement | null = null
    
    // 1. 查找布局滚动容器
    container = document.querySelector('.layout-content-scrollbar .el-scrollbar__wrap') as HTMLElement
    
    // 2. 如果没找到，查找所有 el-scrollbar__wrap（可能有多个，选择最合适的）
    if (!container) {
      const containers = document.querySelectorAll('.el-scrollbar__wrap')
      // 选择有内容的容器（scrollHeight > clientHeight）
      containers.forEach(el => {
        const elm = el as HTMLElement
        if (elm.scrollHeight > elm.clientHeight && !container) {
          container = elm
        }
      })
    }
    
    // 3. 如果还是没找到，使用第一个
    if (!container) {
      container = document.querySelector('.el-scrollbar__wrap') as HTMLElement
    }
    
    if (container) {
      // 创建独立的事件处理函数，便于调试
      // 将容器作为参数传递，确保使用正确的容器数据
      const containerHandler = (e: Event) => {
        if (import.meta.env.DEV) {
          console.log('滚动容器滚动事件触发', {
            scrollTop: container!.scrollTop,
            scrollHeight: container!.scrollHeight,
            clientHeight: container!.clientHeight
          })
        }
        // 传递事件对象，让 handleScroll 知道是哪个容器触发的
        handleScroll(e)
      }
      
      container.addEventListener('scroll', containerHandler, { passive: true })
      scrollListeners.push({ element: container, handler: containerHandler })
    } else {
    }
    
  }, 300) // 延迟300ms确保DOM渲染完成
}

// 移除滚动监听
const removeScrollListener = () => {
  scrollListeners.forEach(({ element, handler }) => {
    if (element === window) {
      window.removeEventListener('scroll', handler)
    } else {
      (element as HTMLElement).removeEventListener('scroll', handler)
    }
  })
  scrollListeners.length = 0
  
  // 清理防抖定时器
  if (scrollTimer) {
    clearTimeout(scrollTimer)
    scrollTimer = null
  }
}

onMounted(() => {
  getGroupList()
  checkIsMobile()
  window.addEventListener('resize', checkIsMobile)
  
  // 根据当前设备类型添加滚动监听
  // 使用 nextTick 确保 DOM 已渲染
  nextTick(() => {
    addScrollListener()
  })
  
  // 监听设备类型变化，动态添加/移除滚动监听
  watch(
    () => isMobile.value,
    (isMobileNow) => {
      if (isMobileNow) {
        nextTick(() => {
          addScrollListener()
        })
      } else {
        removeScrollListener()
      }
    }
  )
  
  // 监听数据变化，确保滚动监听器在数据加载后正确绑定
  watch(
    () => [dataList.value.length, isMobile.value],
    () => {
      if (isMobile.value) {
        nextTick(() => {
          addScrollListener()
        })
      }
    },
    { immediate: true }
  )
  
  // 读取路由查询参数并执行查询
  const searchParam = route.query.search as string
  if (searchParam) {
    // 使用 nextTick 确保组件已经挂载
    nextTick(() => {
      // 设置搜索框的值
      searchRef.value?.setValues({ search: searchParam })
    })
    
    searchParams.value = { search: searchParam }
    currentPage.value = 1
    getList()
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', checkIsMobile)
  removeScrollListener()
  
  // 清理防抖定时器
  if (scrollTimer) {
    clearTimeout(scrollTimer)
    scrollTimer = null
  }
  
  // 清理手机端自动查询的防抖定时器
  if (mobileSearchTimer) {
    clearTimeout(mobileSearchTimer)
    mobileSearchTimer = null
  }
})

const crudSchemas = reactive<CrudSchema[]>([
  /*{
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },*/
{
  field: 'expand',
  type: 'expand',
  search: {
      hidden: true
    },
  slots: {
      default: (data: any) => {
        const { row } = data
        return (
          <div class="ml-30px">
            <div>
              <span>运行天数:{row.days}</span><span style="margin-left: 20px;">余额:{Number(row.balance || 0).toFixed(2)}</span><span style="margin-left: 20px;">备注:{row.remarks}</span>
            </div>
          </div>
        )
      }
    }
  },
  {
    field: 'index',
    label: t('account.index'),
    width: 100,
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
    {
    field: 'id',
    label: t('account.id'),
    hidden: true, // 保持隐藏
    search: {
      component: 'Input',
      hidden: true,
    },
    form: {
      component: 'Input',
      hidden: true,
      colProps: {
        span: 24
      }
    },
    detail: {
      hidden: true,
      span: 24
    }
  },
  {
    field: 'uid',
    label: t('account.uid'),
    width: 120,
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      hidden: true,
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '500px',
          height: '40px',
          fontSize: '16px'
        }
      }
    },
    detail: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          return (
            <div 
              style={`
                color: #409eff; 
                cursor: ${isMobile.value ? 'default' : 'pointer'}; 
                width: 100%;
                height: 100%;
                padding: 8px;
                margin: -8px;
                align-items: center;
                transition: background-color 0.2s;
              `}
              onMouseenter={(e: MouseEvent) => {
                if (!isMobile.value) {
                  const target = e.target as HTMLElement
                  if (target) {
                    target.style.backgroundColor = '#f5f7fa'
                  }
                }
              }}
              onMouseleave={(e: MouseEvent) => {
                if (!isMobile.value) {
                  const target = e.target as HTMLElement
                  if (target) {
                    target.style.backgroundColor = 'transparent'
                  }
                }
              }}
              onClick={() => {
                // 将列表数据存储到 sessionStorage，供详情页使用
                sessionStorage.setItem(`account_row_${data.row.id}`, JSON.stringify(data.row))
                router.push({
                  name: 'accountDetail',
                  query: { id: data.row.id,uid: data.row.uid,days: data.row.days,initial: data.row.initial,itime: data.row.itime,oprid: data.row.oprid,remarks: data.row.remarks,grpName: data.row.grpName,balance: data.row.balance }
                })
              }}
            >
              {data.row.uid}
            </div>
          )
        }
      }
    }
  },
  {
    field: 'search',
    label: t('account.search'),
    hidden: true, // 保持隐藏
    search: {
      component: 'Input',
      hidden: isMobile.value // 在手机端隐藏搜索字段
    },
    form: {
      component: 'Input',
      hidden: true,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center',
    }
  },
  {
    field: 'grpids',
    label: t('account.group'),
    search: {
      component: 'Select',
      componentProps: {
        placeholder: t('account.group')+'名称',
        multiple: true,
        collapseTags: true,
        collapseTagsTooltip: true,
        options: groupOptions,
        on: {
          change: () => {
            // 手机端选中时自动触发查询
            if (isMobile.value) {
              handleMobileAutoSearch()
            }
          }
        }
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'grpName',
    label: t('account.group'),
    width: 120,
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      hidden: true,
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '500px',
          height: '40px',
          fontSize: '16px'
        }
      }
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center',
    }
  },
  {
    field: 'oprName',
    label: t('account.oprName'),
    width: 120,
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      hidden: true,
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '500px',
          height: '40px',
          fontSize: '16px'
        }
      }
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center',
    }
  },
  {
    field: 'balance',
    label: t('account.balance'),
    width: 140,
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      hidden: true,
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '500px',
          height: '40px',
          fontSize: '16px'
        }
      }
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          // 保留2位小数但不四舍五入的函数
          const truncateToTwoDecimals = (num: number | string) => {
            if (num === null || num === undefined || num === '') return '-'
            const numValue = typeof num === 'string' ? parseFloat(num) : num
            if (isNaN(numValue)) return '-'
            // 将数字乘以100，向下取整，再除以100，实现截断而非四舍五入
            return (Math.floor(numValue * 100) / 100).toFixed(2)
          }
          return (
            <div style="position: relative; width: 100%; text-align: center;">
              <span>{truncateToTwoDecimals(data.row.balance)}</span>
            </div>
          )
        },
        header: () => {
          // 只在PC端显示排序箭头
          if (isMobile.value) {
            return <span>{t('account.balance')}</span>
          }
          
          // 获取当前排序状态
          const currentOrder = balanceOrderType.value
          
          return (
            <div 
              style="display: inline-flex; align-items: center; cursor: pointer; user-select: none;" 
              onClick={toggleBalanceSort}
            >
              <span>{t('account.balance')}</span>
              <span class="caret-wrapper" style="display: inline-flex; flex-direction: column; align-items: center; height: 34px; width: 24px; vertical-align: middle; cursor: pointer; overflow: initial; position: relative; margin-left: 4px;">
                <i 
                  class="sort-caret ascending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderBottomColor: currentOrder === 1 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    top: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
                <i 
                  class="sort-caret descending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderTopColor: currentOrder === 0 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    bottom: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
              </span>
            </div>
          )
        }
      }
    }
  },
  {
    field: 'withdraw',
    label: t('finance.withdraw'),
    // width: 160,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          // 保留2位小数但不四舍五入的函数
          const truncateToTwoDecimals = (num: number | string) => {
            if (num === null || num === undefined || num === '') return '-'
            const numValue = typeof num === 'string' ? parseFloat(num) : num
            if (isNaN(numValue)) return '-'
            // 将数字乘以100，向下取整，再除以100，实现截断而非四舍五入
            return (Math.floor(numValue * 100) / 100).toFixed(2)
          }
          return (
            // <div style="position: relative; width: 100%; text-align: left;">
              <div>
              <span>{truncateToTwoDecimals(data.row.withdraw)}</span>
              {/* <BaseButton 
                type="primary" 
                onClick={() => action(data.row, 'edit')}
                style="position: absolute; right: 0; top: 50%; transform: translateY(-50%);"
              >
                <Icon icon="ep:refresh" />
              </BaseButton> */}
            </div>
          )
        },
        header: () => {
          // 只在PC端显示排序箭头
          if (isMobile.value) {
            return <span>{t('finance.withdraw')}</span>
          }
          
          // 获取当前排序状态
          const currentOrder = withdrawOrderType.value
          
          return (
            <div 
              style="display: inline-flex; align-items: center; cursor: pointer; user-select: none;" 
              onClick={toggleWithdrawSort}
            >
              <span>{t('finance.withdraw')}</span>
              <span class="caret-wrapper" style="display: inline-flex; flex-direction: column; align-items: center; height: 34px; width: 24px; vertical-align: middle; cursor: pointer; overflow: initial; position: relative; margin-left: 4px;">
                <i 
                  class="sort-caret ascending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderBottomColor: currentOrder === 1 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    top: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
                <i 
                  class="sort-caret descending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderTopColor: currentOrder === 0 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    bottom: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
              </span>
            </div>
          )
        }
      }
    }
  },
  {
    field: 'witNum',
    label: t('finance.witNum'),
    // width: 160,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          return (
              <div>
              <span>{data.row.witNum}</span>
            </div>
          )
        },
        header: () => {
          // 只在PC端显示排序箭头
          if (isMobile.value) {
            return <span>{t('finance.witNum')}</span>
          }
          
          // 获取当前排序状态
          const currentOrder = expenditureOrderType.value
          
          return (
            <div 
              style="display: inline-flex; align-items: center; cursor: pointer; user-select: none;" 
              onClick={toggleExpenditureSort}
            >
              <span>{t('finance.witNum')}</span>
              <span class="caret-wrapper" style="display: inline-flex; flex-direction: column; align-items: center; height: 34px; width: 24px; vertical-align: middle; cursor: pointer; overflow: initial; position: relative; margin-left: 4px;">
                <i 
                  class="sort-caret ascending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderBottomColor: currentOrder === 1 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    top: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
                <i 
                  class="sort-caret descending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderTopColor: currentOrder === 0 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    bottom: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
              </span>
            </div>
          )
        }
      }
    }
  },
  {
    field: 'deposit',
    label: t('finance.deposit'),
    // width: 160,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          return (
              <div>
              <span>{data.row.deposit}</span>
            </div>
          )
        },
        header: () => {
          // 只在PC端显示排序箭头
          if (isMobile.value) {
            return <span>{t('finance.deposit')}</span>
          }
          
          // 获取当前排序状态
          const currentOrder = depositOrderType.value
          
          return (
            <div 
              style="display: inline-flex; align-items: center; cursor: pointer; user-select: none;" 
              onClick={toggleDepositSort}
            >
              <span>{t('finance.deposit')}</span>
              <span class="caret-wrapper" style="display: inline-flex; flex-direction: column; align-items: center; height: 34px; width: 24px; vertical-align: middle; cursor: pointer; overflow: initial; position: relative; margin-left: 4px;">
                <i 
                  class="sort-caret ascending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderBottomColor: currentOrder === 1 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    top: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
                <i 
                  class="sort-caret descending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderTopColor: currentOrder === 0 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    bottom: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
              </span>
            </div>
          )
        }
      }
    }
  },
    {
    field: 'income',
    label: t('account.revenue'),
    // width: 160,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          // 保留2位小数但不四舍五入的函数
          const truncateToTwoDecimals = (num: number | string) => {
            if (num === null || num === undefined || num === '') return '-'
            const numValue = typeof num === 'string' ? parseFloat(num) : num
            if (isNaN(numValue)) return '-'
            // 将数字乘以100，向下取整，再除以100，实现截断而非四舍五入
            return (Math.floor(numValue * 100) / 100).toFixed(2)
          }
          return (
            // <div style="position: relative; width: 100%; text-align: left;">
              <div>
              <span>{truncateToTwoDecimals(data.row.income)}</span>
              {/* <BaseButton 
                type="primary" 
                onClick={() => action(data.row, 'edit')}
                style="position: absolute; right: 0; top: 50%; transform: translateY(-50%);"
              >
                <Icon icon="ep:refresh" />
              </BaseButton> */}
            </div>
          )
        },
        header: () => {
          // 只在PC端显示排序箭头
          if (isMobile.value) {
            return <span>{t('account.revenue')}</span>
          }
          
          // 获取当前排序状态
          const currentOrder = incomeOrderType.value
          
          return (
            <div 
              style="display: inline-flex; align-items: center; cursor: pointer; user-select: none;" 
              onClick={toggleIncomeSort}
            >
              <span>{t('account.revenue')}</span>
              <span class="caret-wrapper" style="display: inline-flex; flex-direction: column; align-items: center; height: 34px; width: 24px; vertical-align: middle; cursor: pointer; overflow: initial; position: relative; margin-left: 4px;">
                <i 
                  class="sort-caret ascending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderBottomColor: currentOrder === 1 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    top: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
                <i 
                  class="sort-caret descending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderTopColor: currentOrder === 0 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    bottom: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
              </span>
            </div>
          )
        }
      }
    }
  },
  {
    field: 'expenditure',
    label: t('account.totalLoss'),
    // width: 160,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          // 保留2位小数但不四舍五入的函数
          const truncateToTwoDecimals = (num: number | string) => {
            if (num === null || num === undefined || num === '') return '-'
            const numValue = typeof num === 'string' ? parseFloat(num) : num
            if (isNaN(numValue)) return '-'
            return (Math.floor(numValue * 100) / 100).toFixed(2)
          }
          return (
              <div>
              <span>{truncateToTwoDecimals(data.row.expenditure)}</span>
            </div>
          )
        },
        header: () => {
          // 只在PC端显示排序箭头
          if (isMobile.value) {
            return <span>{t('account.totalLoss')}</span>
          }
          
          // 获取当前排序状态
          const currentOrder = expenditureOrderType.value
          
          return (
            <div 
              style="display: inline-flex; align-items: center; cursor: pointer; user-select: none;" 
              onClick={toggleExpenditureSort}
            >
              <span>{t('account.totalLoss')}</span>
              <span class="caret-wrapper" style="display: inline-flex; flex-direction: column; align-items: center; height: 34px; width: 24px; vertical-align: middle; cursor: pointer; overflow: initial; position: relative; margin-left: 4px;">
                <i 
                  class="sort-caret ascending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderBottomColor: currentOrder === 1 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    top: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
                <i 
                  class="sort-caret descending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderTopColor: currentOrder === 0 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    bottom: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
              </span>
            </div>
          )
        }
      }
    }
  },
  {
    field: 'lastexp',
    label: t('account.lastexp'),
    // width: 160,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          // 保留2位小数但不四舍五入的函数
          const truncateToTwoDecimals = (num: number | string) => {
            if (num === null || num === undefined || num === '') return '-'
            const numValue = typeof num === 'string' ? parseFloat(num) : num
            if (isNaN(numValue)) return '-'
            // 将数字乘以100，向下取整，再除以100，实现截断而非四舍五入
            return (Math.floor(numValue * 100) / 100).toFixed(2)
          }
          return (
            // <div style="position: relative; width: 100%; text-align: left;">
            <div>
              <span>{truncateToTwoDecimals(data.row.lastexp)}</span>
            </div>
          )
        },
        header: () => {
          // 只在PC端显示排序箭头
          if (isMobile.value) {
            return <span>{t('account.lastexp')}</span>
          }
          
          // 获取当前排序状态
          const currentOrder = lastexpOrderType.value
          
          return (
            <div 
              style="display: inline-flex; align-items: center; cursor: pointer; user-select: none;" 
              onClick={toggleLastexpSort}
            >
              <span>{t('account.lastexp')}</span>
              <span class="caret-wrapper" style="display: inline-flex; flex-direction: column; align-items: center; height: 34px; width: 24px; vertical-align: middle; cursor: pointer; overflow: initial; position: relative; margin-left: 4px;">
                <i 
                  class="sort-caret ascending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderBottomColor: currentOrder === 1 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    top: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
                <i 
                  class="sort-caret descending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderTopColor: currentOrder === 0 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    bottom: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
              </span>
            </div>
          )
        }
      }
    }
  },
  {
    field: 'avgexp',
    label: t('account.avgexp'),
    // width: 160,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          // 保留2位小数但不四舍五入的函数
          const truncateToTwoDecimals = (num: number | string) => {
            if (num === null || num === undefined || num === '') return '-'
            const numValue = typeof num === 'string' ? parseFloat(num) : num
            if (isNaN(numValue)) return '-'
            // 将数字乘以100，向下取整，再除以100，实现截断而非四舍五入
            return (Math.floor(numValue * 100) / 100).toFixed(2)
          }
          return (
            // <div style="position: relative; width: 100%; text-align: left;">
            <div>
              <span>{truncateToTwoDecimals(data.row.avgexp)}</span>
            </div>
          )
        },
        header: () => {
          // 只在PC端显示排序箭头
          if (isMobile.value) {
            return <span>{t('account.avgexp')}</span>
          }
          
          // 获取当前排序状态
          const currentOrder = avgexpOrderType.value
          
          return (
            <div 
              style="display: inline-flex; align-items: center; cursor: pointer; user-select: none;" 
              onClick={toggleAvgexpSort}
            >
              <span>{t('account.avgexp')}</span>
              <span class="caret-wrapper" style="display: inline-flex; flex-direction: column; align-items: center; height: 34px; width: 24px; vertical-align: middle; cursor: pointer; overflow: initial; position: relative; margin-left: 4px;">
                <i 
                  class="sort-caret ascending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderBottomColor: currentOrder === 1 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    top: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
                <i 
                  class="sort-caret descending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderTopColor: currentOrder === 0 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    bottom: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
              </span>
            </div>
          )
        }
      }
    }
  },
    {
    field: 'days',
    label: t('account.days'),
    width: 123,
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      hidden: true,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          return (
              <div>
              <span>{data.row.days}</span>
            </div>
          )
        },
        header: () => {
          // 只在PC端显示排序箭头
          if (isMobile.value) {
            return <span>{t('account.days')}</span>
          }
          
          // 获取当前排序状态
          const currentOrder = daysOrderType.value
          
          return (
            <div 
              style="display: inline-flex; align-items: center; cursor: pointer; user-select: none;" 
              onClick={toggleDaysSort}
            >
              <span>{t('account.days')}</span>
              <span class="caret-wrapper" style="display: inline-flex; flex-direction: column; align-items: center; height: 34px; width: 24px; vertical-align: middle; cursor: pointer; overflow: initial; position: relative; margin-left: 4px;">
                <i 
                  class="sort-caret ascending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderBottomColor: currentOrder === 1 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    top: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
                <i 
                  class="sort-caret descending"
                  style={{
                    width: 0,
                    height: 0,
                    border: '5px solid transparent',
                    borderTopColor: currentOrder === 0 ? '#409eff' : '#c0c4cc',
                    position: 'absolute',
                    bottom: '5px',
                    left: '7px',
                    cursor: 'pointer',
                    transition: 'all 0.2s'
                  }}
                />
              </span>
            </div>
          )
        }
      }
    }
  },
  {
    field: 'itime',
    label: t('account.itime'),
    width: 140,
    search: {
      hidden: true
    },
    form: {
      component: 'DatePicker',
      colProps: {
        span: 24
      },
      componentProps: {
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        format: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  {
    field: 'btime',
    label: t('account.btime'),
    width: 140,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
    {
    field: 'status',
    label: t('finance.status'),
    width: 140,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  {
    field: 'remarks',
    label: t('account.remarks'),
    width: 140,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  {
    field: 'oprid',
    label: t('account.operator'),
    width: 80,
    hidden: true, // 显示这个字段
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      colProps: {
        span: 24
      },
      componentProps: {
        props: {
          label: 'name',
          value: 'id'
        }
      },
      optionApi: async () => {
        try {
          console.log('正在请求操作员列表...')
          const res = await operatorNameApi()
          console.log('操作员列表响应:', res)
          // 根据实际返回的数据结构调整
          if (res.data) {
            return Array.isArray(res.data) ? res.data : (res.data.items || [])
          }
          return []
        } catch (error) {
          console.error('获取操作员列表失败:', error)
          return []
        }
      }
    },
    detail: {
      span: 24
    },
    table: {
      align: 'center',
      headerAlign: 'center'
    }
  },
  {
    field: 'action',
    width: '140px',
    label: t('finance.depositlog'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      align: 'center',
      headerAlign: 'center',
      slots: {
        default: (data: any) => {
          return (
            <>
              {/* <BaseButton type="primary" onClick={() => action(data.row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton> */}
              <BaseButton style="background-color: #409EFF; border-color: #409EFF;" onClick={() => calendar(data.row, 'calendar')}>
                <Icon icon="ep:document" color="#ffffff" />
              </BaseButton>
              {/* <BaseButton type="danger" onClick={() => delData(data.row)}>
                {t('exampleDemo.del')}
              </BaseButton> */}
            </>
          )
        }
      }
    }
  }
])

// 创建响应式的 schemas
const allSchemas = computed(() => {
  // 动态修改字段的 hidden 属性
  const dynamicCrudSchemas = crudSchemas.map(schema => {
    // 在手机端隐藏带有 mobile-hidden 类名的字段，通过 hidden 属性完全不渲染
    const shouldHideOnMobile = isMobile.value && (
      schema.field === 'id' ||
      schema.field === 'search' ||
      schema.field === 'expenditure' ||
      schema.field === 'lastexp' ||
      schema.field === 'avgexp' ||
      schema.field === 'refresh' ||
      schema.field === 'avgprofit' ||
      schema.field === 'index' || // 手机端隐藏原本的序号列，因为selection会变成序号
      schema.field === 'grpName' ||
      schema.field === 'initial' ||
      schema.field === 'itime' ||
      schema.field === 'days' ||
      schema.field === 'revenue' ||
      schema.field === 'profit' ||
      schema.field === 'score' ||
      schema.field === 'btime' ||
      schema.field === 'action' ||
      schema.field === 'runningDays' || // 手机端隐藏单独的运行天数列
      schema.field === 'balance' || // 手机端隐藏单独的余额列
      schema.field === 'remarks' // 手机端隐藏单独的备注列
    )
    // 在手机端只显示分组筛选，隐藏其他搜索字段
    if (schema.field === 'keywords') {
      return {
        ...schema,
        search: {
          ...schema.search,
          hidden: isMobile.value // 手机端隐藏keywords搜索
        }
      }
    }

    // 特殊处理 selection 字段：在手机端改为序号显示
    if (schema.field === 'selection') {
      return {
        ...schema,
        label: isMobile.value ? t('account.index') : '', // 手机端显示"序号"标签，PC端为空
        table: {
          ...schema.table,
          type: isMobile.value ? 'index' : 'selection' // 手机端显示为序号，PC端显示为多选框
        }
      }
    }

    // 特殊处理 expand 字段：只在手机端显示，PC端隐藏
    if (schema.field === 'expand') {
      return {
        ...schema,
        hidden: !isMobile.value, // PC端隐藏，手机端显示
        table: {
          ...schema.table,
          hidden: !isMobile.value // PC端隐藏，手机端显示
        }
      }
    }

    // 应用响应式隐藏逻辑
    if (shouldHideOnMobile) {
      return {
        ...schema,
        hidden: true, // 在响应式模式下完全隐藏字段
        table: {
          ...schema.table,
          hidden: true
        }
      }
    }

    return schema
  })
  
  // @ts-ignore
  return useCrudSchemas(dynamicCrudSchemas).allSchemas
})

const dialogVisible = ref(false)
const dialogCalendarVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<TableData | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const delLoading = ref(false)
const allRefreshLoading = ref(false)

const delData = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const calendar = (row: TableData, type: string) => {
  dialogTitle.value = t('finance.depositlog')
  actionType.value = type
  currentRow.value = row
  dialogCalendarVisible.value = true
}
const action = (row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'account.edit' : 'account.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()
const searchRef = ref()

const saveLoading = ref(false)

const refresh = async (row: TableData | null) => {
  if (!row) return
  
  // 设置当前行的加载状态
  refreshLoading.value[row.id] = true
  
  try {
    const res = await refreshUserBalanceApi({
      id: row.id,
    })
    
    if (res && res.data) {
      // 只更新当前行的数据，而不是刷新整个表格
      const index = dataList.value.findIndex(item => item.id === row.id)
      if (index !== -1) {
        // 更新当前行的数据
        dataList.value[index] = { ...dataList.value[index], ...res.data }
      }
    }
  } catch (error) {
    console.error('刷新失败:', error)
  } finally {
    // 清除加载状态
    refreshLoading.value[row.id] = false
  }
}
const allrefresh = async (row: TableData | null) => {
  allRefreshLoading.value = true
  try {
    // 获取当前分页的全部id值，转换为字符串数组
    const refreshIds = row ? [row.id.toString()] : dataList.value.map((v: TableData) => v.id.toString()) || []
    const res = await allrefreshUserBalanceApi({
      ids: refreshIds,
    });

    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  } catch (error) {
    console.error('刷新全部失败:', error)
  } finally {
    allRefreshLoading.value = false
  }
}
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveTableApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}

// 账户总余额（使用接口返回的 balSum 字段）
const totalBalance = computed(() => {
  return balSum.value || 0
})
// 账户总耗损（使用接口返回的 expSum 字段）
const totalExpSum = computed(() => {
  return expSum.value || 0
})
// 账户总收益（使用接口返回的 incSum 字段）
const totalinSum = computed(() => {
  return incSum.value || 0
})

// 格式化余额显示（保留2位小数）
const formatBalance = (balance: number) => {
  return balance.toLocaleString('en-US', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 导出数据功能
const exportLoading = ref(false)
const exportData = async () => {
  try {
    exportLoading.value = true
    
    // 构建请求参数，包含当前搜索条件和导出参数
    const requestParams: any = {
      export: 1,
      ...unref(searchParams)
    }
    
    // 调用列表接口，传入 export=1 参数
    const res = await getTableListApi(requestParams)
    
    if (res && res.data) {
      // 获取返回的下载URL
      const downloadUrl = res.data.url || res.data.downloadUrl || res.data.fileUrl
      
      if (downloadUrl) {
        // 处理URL：如果是相对路径，转换为绝对路径
        let finalUrl = downloadUrl
        if (!downloadUrl.startsWith('http://') && !downloadUrl.startsWith('https://')) {
          // 如果是相对路径，拼接当前域名和基础路径
          const baseURL = import.meta.env.VITE_API_BASE_PATH || ''
          const origin = window.location.origin
          if (downloadUrl.startsWith('/')) {
            // 绝对路径，直接拼接域名
            finalUrl = origin + downloadUrl
          } else {
            // 相对路径，需要拼接基础路径
            finalUrl = origin + (baseURL ? baseURL + '/' : '/') + downloadUrl
          }
        }
        
        // 创建隐藏的链接并触发下载
        const link = document.createElement('a')
        link.href = finalUrl
        link.download = '' // 让浏览器使用服务器返回的文件名
        link.target = '_blank' // 在新窗口打开，确保下载
        link.style.display = 'none'
        document.body.appendChild(link)
        link.click()
        
        // 延迟移除，确保下载开始
        setTimeout(() => {
          document.body.removeChild(link)
        }, 100)
        
        ElMessage.success('导出成功，正在下载...')
      } else {
        ElMessage.error('导出失败: 接口未返回下载URL')
        console.error('导出失败: 接口未返回下载URL', res)
      }
    } else {
      ElMessage.error('导出失败: 接口返回数据异常')
      console.error('导出失败: 接口返回数据异常', res)
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  } finally {
    exportLoading.value = false
  }
}
</script>

<template>
  <ContentWrap>
    <div class="search-container">
      <Search 
        :schema="allSchemas.searchSchema" 
        :show-search="!isMobile"
        :show-reset="!isMobile"
        @search="setSearchParams" 
        @reset="setSearchParams" 
        @register="searchRef = $event"
      />
      
      <!-- PC端账户总余额和导出按钮 -->
      <div v-if="!isMobile" class="balance-export-section">
        <div class="balance-info">
          <!-- <div class="balance-icon">
            <span class="dollar-icon">$</span>
          </div> -->
          <!--<span class="balance-label">账号总余额:</span>
          <span class="balance-value">${{ formatBalance(totalBalance) }}</span>
          <span class="balance-label">账号总收益:</span>
          <span class="balance-value">${{ formatBalance(totalinSum) }}</span>
          <span class="balance-label">账号总耗损:</span>
          <span class="balance-value">${{ formatBalance(totalExpSum) }}</span>-->
          <div class="balance-row">
            <span class="balance-label">余额:</span>
            <span class="balance-value">${{ formatBalance(totalBalance) }}</span>
            <span class="balance-label">充值:</span>
            <span class="balance-value">${{ formatBalance(deposit) }}</span>
            <span class="balance-label">提现:</span>
            <span class="balance-value">${{ formatBalance(withdraw) }}</span>
          </div>
          <div class="balance-row">
            <span class="balance-label">收益:</span>
            <span class="balance-value">${{ formatBalance(totalinSum) }}</span>
            <span class="balance-label">耗损:</span>
            <span class="balance-value">${{ formatBalance(totalExpSum) }}</span>
            <span class="balance-label">亏损账号数量:</span>
            <span class="balance-value">{{ lossNum }}</span>
          </div>
        </div>
        <BaseButton type="primary" :loading="exportLoading" @click="exportData" class="export-btn">
          导出
        </BaseButton>
      </div>
    </div>

    <!-- <div class="mb-10px" :class="{ 'mobile-hidden-buttons': isMobile }"> -->
       <!--<BaseButton type="primary" @click="AddAction">{{ t('account.add') }}</BaseButton> -->
      <!-- <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('account.del') }}
      </BaseButton> -->
      <!-- <BaseButton :loading="allRefreshLoading" type="primary" @click="allrefresh(null)">
        <Icon v-if="allRefreshLoading" icon="ep:loading" class="loading-icon" />
        {{ t('account.refreshALL') }}
      </BaseButton> -->
    <!-- </div> -->

    <Table
      :key="tableKey"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="isMobile ? undefined : {
        total: total,
        layout: '->, total, sizes, prev, pager, next, jumper'
      }"
      @register="tableRegister"
    />
    
    <!-- 手机端上拉加载提示 -->
    <div v-if="isMobile" class="mobile-load-more">
      <div v-if="isLoadingMore" class="loading-text">
        <Icon icon="ep:loading" class="loading-icon" />
        正在加载更多...
      </div>
      <div v-else-if="!hasMoreData && dataList.length > 0" class="no-more-text">
        没有更多数据了
      </div>
      <div v-else-if="hasMoreData && dataList.length > 0" class="pull-up-text">
        上拉加载更多
      </div>
    </div>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :maxHeight="480">
    <Write
      v-if="actionType === 'edit' || actionType === 'add'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />
    <Calendar
      v-if="actionType === 'calendar'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <div v-if="actionType === 'calendar'">
        <!-- <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton> -->
      </div>
      <div v-else-if="actionType === 'edit'" style="display: flex; justify-content: space-between; align-items: center;">
        <!-- <BaseButton :loading="delLoading" type="danger" @click="delData(currentRow)">
          {{ t('exampleDemo.del') }}
        </BaseButton> -->
        <div>
          <BaseButton
            type="primary"
            :loading="saveLoading"
            @click="save"
            style="margin-right: 8px;"
          >
            {{ t('exampleDemo.save') }}
          </BaseButton>
          <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
        </div>
      </div>
      <div v-else>
        <BaseButton
          type="primary"
          :loading="saveLoading"
          @click="save"
          style="margin-right: 8px;"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </div>
    </template>
  </Dialog>
  <Dialog v-model="dialogCalendarVisible" :title="dialogTitle" width="800px" :maxHeight="640">
    <Iohistory
      v-if="actionType === 'calendar'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />
  </Dialog>
</template>

<style scoped>
/* 搜索容器布局 */
.search-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 16px;
}

/* 搜索组件宽度调整 */
.search-container :deep(.el-form) {
  flex: 1;
  min-width: 0;
}

/* PC端账户总余额和导出按钮区域 */
.balance-export-section {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-shrink: 0;
  margin-top: 8px;
  white-space: nowrap;
}

/* 余额信息容器 */
.balance-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 余额行 */
.balance-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 余额图标 */
.balance-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(255, 215, 0, 0.3);
}

.dollar-icon {
  color: #ffffff;
  font-size: 18px;
  font-weight: bold;
  line-height: 1;
}

/* 余额标签 */
.balance-label {
  color: #606266;
  font-size: 14px;
}

/* 余额值 */
.balance-value {
  color: #409EFF;
  font-size: 14px;
  font-weight: 500;
}

/* 导出按钮 */
.export-btn {
  border-radius: 4px;
}

/* :deep(.el-form-item__label) {
  font-size: 16px !important;
  line-height: 32px !important;
  display: flex !important;
  align-items: center !important;
} */

:deep(.el-form-item__content) {
  display: flex !important;
  align-items: center !important;
}

:deep(.el-input) {
  display: flex !important;
  align-items: center !important;
}

:deep(.el-input__wrapper) {
  display: flex !important;
  align-items: center !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  /* 在手机端隐藏操作按钮组 */
  .mobile-hidden-buttons {
    display: none !important;
  }
  
  /* 手机端表格行高度调整，适应多行内容 */
  :deep(.el-table .el-table__row) {
    height: auto !important;
  }
  
  :deep(.el-table .el-table__cell) {
    padding: 12px 8px !important;
    line-height: 1.4 !important;
  }
  
  /* 手机端账户信息显示样式优化 */
  :deep(.el-table .mobile-account-info) {
    text-align: left !important;
    line-height: 1.6 !important;
  }
  
  :deep(.el-table .mobile-account-info .account-name) {
    font-weight: bold !important;
    color: #409eff !important;
    margin-bottom: 4px !important;
    font-size: 14px !important;
  }
  
  :deep(.el-table .mobile-account-info .account-details) {
    font-size: 12px !important;
    color: #666 !important;
    display: flex !important;
    flex-wrap: wrap !important;
    gap: 12px !important;
    margin-bottom: 2px !important;
  }
  
  :deep(.el-table .mobile-account-info .account-remarks) {
    font-size: 11px !important;
    color: #888 !important;
    margin-top: 2px !important;
    word-break: break-all !important;
  }
  
  /* 手机端搜索表单样式优化 - 只显示分组筛选 */
  :deep(.el-form--inline) {
    display: flex !important;
    flex-direction: column !important;
    /* gap: 15px !important; */
    /* padding: 15px !important; */
    background-color: #f8f9fa !important;
    border-radius: 8px !important;
    margin-bottom: 15px !important;
  }
  
  :deep(.el-form--inline .el-form-item) {
    display: flex !important;
    flex-direction: column !important;
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 0 !important;
  }
  
  :deep(.el-form--inline .el-form-item__label) {
    display: none !important;
  }
  
  :deep(.el-form--inline .el-form-item__content) {
    flex: 1 !important;
    margin-left: 0 !important;
  }
  
  /* 确保分组选择器在手机端全宽显示且样式美观 */
  :deep(.el-form--inline .el-select) {
    width: 100% !important;
  }
  
  :deep(.el-form--inline .el-select .el-input) {
    width: 100% !important;
  }
  
  :deep(.el-form--inline .el-select .el-input__wrapper) {
    width: 100% !important;
    height: 44px !important;
    font-size: 16px !important;
  }
  
  /* 手机端上拉加载提示样式 */
  .mobile-load-more {
    text-align: center !important;
    padding: 20px !important;
    color: #666 !important;
    font-size: 14px !important;
  }
  
  .loading-text {
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    gap: 8px !important;
  }
  
  .loading-icon {
    animation: spin 1s linear infinite !important;
  }
  
  @keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
  }
  
  .no-more-text {
    color: #999 !important;
  }
  
  .pull-up-text {
    color: #409eff !important;
  }
}

/* PC端保持原有样式 */
@media (min-width: 769px) {
  .mobile-load-more {
    display: none !important;
  }
}
</style>
